#include "List.h"


LTNode* LTBuyNode(LTDataType x)
{
	LTNode* newnode = (LTNode*)malloc(sizeof(LTNode));
	if (newnode == NULL)
	{
		perror("malloc");
		exit(1);
	}
	newnode->data = x;
	newnode->next = newnode->prev = newnode;
	return newnode;
}

//void LTInit(LTNode** pphead)
//{
//	*pphead = LTBuyNode(-1);
//}
LTNode* LTInit()
{
	LTNode* newhead = LTBuyNode(-1);
	return newhead;
}

void LTPushBack(LTNode* phead, LTDataType x)
{
	assert(phead);
	LTNode* newnode = LTBuyNode(x);
	LTNode* ptail = phead->prev;
	ptail->next = newnode;
	newnode->prev = ptail;
	newnode->next = phead;
	phead->prev = newnode;
}


void LTPushFront(LTNode* phead, LTDataType x)
{
	assert(phead);
	LTNode* pcur = phead->next;
	LTNode* newnode = LTBuyNode(x);
	phead->next = newnode;
	newnode->prev = phead;
	newnode->next = pcur;
	pcur->prev = newnode;
}

void LTPopBack(LTNode* phead)
{
	assert(!LTEmpty(phead));
	LTNode* ptail = phead->prev;
	LTNode* pcur = ptail->prev;
	phead->prev = pcur;
	pcur->next = phead;
	free(ptail);
	ptail = NULL;
}

bool LTEmpty(LTNode* phead)
{
	assert(phead);
	return phead->next == phead;
}

void LTPopFront(LTNode* phead)
{
	assert(!LTEmpty(phead));
	LTNode* pcur = phead->next;
	LTNode* pnext = pcur->next;
	pnext->prev = phead;
	phead->next = pnext;
	free(pcur);
	pcur = NULL;
}

void LTPrint(LTNode* phead)
{
	assert(phead);
	LTNode* pcur = phead->next;
	while (pcur != phead)
	{
		printf("%d -> ", pcur->data);
		pcur = pcur->next;
	}
	printf("\n");
}

LTNode* LTFind(LTNode* phead, LTDataType x)
{
	assert(phead);
	LTNode* pcur = phead->next;
	while (pcur != phead)
	{
		if (pcur == NULL)
		{
			return NULL;
		}
		if (pcur->data == x)
		{
			return pcur;
		}
		pcur = pcur->next;
	}
	return NULL;
}

void LTInsert(LTNode* pos, LTDataType x)
{
	assert(pos && pos->next != pos);
	LTNode* pcur = pos->next;
	LTNode* newnode = LTBuyNode(x);
	newnode->prev = pos;
	newnode->next = pcur;
	pos->next = newnode;
	pcur->prev = newnode;
}


void LTErase(LTNode* pos)
{
	assert(pos && pos->next != pos);
	LTNode* pcur = pos->prev;
	LTNode* pnext = pos->next;
	pcur->next = pnext;
	pnext->prev = pcur;
	free(pos);
	pos = NULL;
}


//void LTDestroy(LTNode** pphead)
//{
//	LTNode* pcur = (*pphead)->next;
//	while (pcur != *pphead)
//	{
//		LTNode* pfree = pcur;
//	    pcur = pcur->next;
//		free(pfree);
//		pfree = NULL;
//	}
//	free(*pphead);
//	*pphead = NULL;
//}
//
////void LTDesTroy(LTNode** phead)
////{
////	LTNode* pcur = (*phead)->next;
////	while (pcur != *phead)
////	{
////		LTNode* pfree = pcur->next;
////		free(pcur);
////		pcur = pfree;
////	}
////	free(*phead);
////	*phead = NULL;
////}

void LTDestroy(LTNode* phead)
{
	LTNode* pcur = (phead)->next;
	while (pcur != phead)
	{
		LTNode* pfree = pcur;
		pcur = pcur->next;
		free(pfree);
		pfree = NULL;
	}
	free(phead);
	phead = NULL;
}


